#!/usr/bin/python
#coding:utf-8

import matplotlib.pylab as plt
from matplotlib.widgets import MultiCursor
from matplotlib.widgets import SpanSelector
from matplotlib.widgets import CheckButtons
from matplotlib.widgets import Button

import matplotlib.ticker as ticker
import numpy as npy
import string
import time,datetime

import tkFileDialog

#中文字体设置
plt.mpl.rcParams['font.sans-serif'] = ['SimHei']
plt.mpl.rcParams['axes.unicode_minus'] = False

#窗口框架
fig = plt.figure(u'线下分析软件', figsize=(20, 10))
ax1 = fig.add_subplot(211, axisbg='#FFFFCC')
ax2 = fig.add_subplot(212, axisbg='#FFFFCC')

#按键
resetax = plt.axes([0.1, 0.92, 0.06, 0.04]) #位置、大小
button = Button(resetax, 'Open', hovercolor='0.975')
def reset(event):
    # add your code
    filename = tkFileDialog.askopenfilename(initialdir = './')
    #plt.title(filename, fontsize=8,fontdict=dict(horizontalalignment="right"), bbox=dict(facecolor="yellow"))
    #fig.set_label(filename)
    ax1.clear()
    ax2.clear()
    main(filename)
button.on_clicked(reset)
####

#Default Open file name
filename = tkFileDialog.askopenfilename(initialdir = './')

    #import pdb
    #pdb.set_trace()
    #fig.suptitle(filename)
    #plt.title(filename, fontsize=8,fontdict=dict(horizontalalignment="right"), bbox=dict(facecolor="yellow"))
    #转换为2进制
def tobin(data):
    a = "%10s" % (bin(int(data, 16)))
    #a = "%10s" % ( bin(253))
    a = a.replace(' ', '0')
    a = a.replace('b', '0')
    a = a[-8:]
    return a


def main(filename):
    tm = [] #时间序列
    ch = [] #数据序列
    labels=[]
    #checks=[]
    for i in range(0, 22):
        tm.append([])
        ch.append([])
        #labels.append(u"通道 "+str(i))
        #checks.append(True)
    labels=[
            u"K12线圈",
            u"锁匙开关a",
            u"锁匙开关b",
            u"折返按钮",
            u"ATO按钮a",
            u"ATO按钮b",
            u"门锁闭a",
            u"门锁闭b",
            u"左门允许",
            u"右门允许",
            u"紧制信号a",
            u"紧制信号b",
            u"方向手柄a",
            u"方向手柄b",
            u"ATP收",
            u"ATP发",
            u"折返信号",
            u"ATO模式",
            u"ATO制动",
            u"ATO牵引",
            u"K5线圈",
            u"牵引输出",
            ]


    begin = 0;
    end = 0;
    #print ch
    nline = 0
    t_start=time.time() #获取当前时间戳，用于计算处理时
    for line in open(filename):
        nline = nline + 1
        #data = filter(lambda x: x in string.printable, line).split()
        data = line.split()
        if len(data) < 6:
            try:
                h, m, s, ms = data[0].lstrip('\0 ').replace(':', '.').split('.')
            except Exception as err:
                print nline, line
                #print data[0]
                continue
            #h, m, s, ms = data[0].replace(':', '.').split('.')
            #print h,m,s,ms
            try:
                xpos = int(h) * 3600 + int(m) * 60 + int(s) + float(ms) / 1000
            except Exception as err:
                print nline, line
                #print data[0]
                continue
            if begin == 0:
                begin = xpos
            if end < xpos:
                end = xpos

            #import pdb
            #pdb.set_trace()
            #print data[1],data[2],data[3]
            d = tobin(data[1]) + tobin(data[2]) + tobin(data[3])
            for i in range(0, 22):
                tmp=int(d[i])+ (21.5-i) * 2 #位置调整
                if len(ch[i]) < 1:
                    ch[i].append(tmp)
                    tm[i].append(xpos)
                else:
                    if ch[i][-1] != tmp: # changed
                        ch[i].append(ch[i][-1])
                        ch[i].append(tmp)
                        tm[i].append(xpos)
                        tm[i].append(xpos)
                    else:
                        ch[i].append(tmp)
                        tm[i].append(xpos)


    print '运行时间'+str(time.time()-t_start)

    im1=[]
    im2=[]

    for i in range(0, 22):
        im, = ax1.plot(tm[i], ch[i],label=labels[i])
        im1.append(im)
        im, = ax2.plot(tm[i], ch[i])
        im2.append(im)

    #rect = plt.bar(left = (0,1),height = (1,0.5),width = 0.35,align="center")
    #ax1.set_title('123')
    #ax2.set_title('321')
    leg = ax1.legend(im1,labels,bbox_to_anchor=(-0.08, 1), fancybox=True, shadow=True,fontsize='medium')  #图例
    #leg.get_frame().set_alpha(0.4)  #设置背景透明度
    lined = dict()
    for legline, origline in zip(leg.get_lines(), im1):
        legline.set_picker(5)  # 5 pts tolerance设置有效点击范围（允许误差为5素）
        lined[legline] = origline
        
    def onpick(event):
        # on the pick event, find the orig line corresponding to the
        # legend proxy line, and toggle the visibility
        legline = event.artist
        origline = lined[legline]
        vis = not origline.get_visible()  #将可见状态取反
        origline.set_visible(vis)
        # Change the alpha on the line in the legend so we can see what lines
        # have been toggled
        if vis:
            legline.set_alpha(1.0)
        else:
            legline.set_alpha(0.2)
        fig.canvas.draw()

    fig.canvas.mpl_connect('pick_event', onpick)

    


    ax1.set_xlim(begin, end)
    #ax1.set_ylim(0, 46)
    ax2.set_xlim(begin, end)
    #ax2.set_ylim(0, 46)


    def onselect1(xmin, xmax):
        indmin, indmax = npy.searchsorted(tm[0], (xmin, xmax))
        print xmin, xmax
        print indmin, indmax
        ax2.set_xlim(xmin, xmax)
        fig.canvas.draw()

    def onselect2(xmin, xmax):
        indmin, indmax = npy.searchsorted(tm[0], (xmin, xmax))
        print xmin, xmax
        print indmin, indmax
        ax2.set_xlim(xmin, xmax)
        fig.canvas.draw()

    plt.grid()#显示栅格
    plt.subplots_adjust(left=0.15,right=0.99,bottom=0.05, top=0.98,hspace=0.05)

    #左边选择栏


    #时间轴
    def format_date(x, pos):
        h=x/3600
        m=x%3600/60
        s=float(x)%60
        return "%02d:%02d:%02.03f" % (h,m,s)
    
    ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    ax2.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))

    ax1.yaxis.set_ticklabels("")
    ax2.yaxis.set_ticklabels("")
    fig.autofmt_xdate()
    

    #cursor = Cursor(ax2, useblit=True, color='red', linewidth=0.5 )
    multi = MultiCursor(fig.canvas, (ax1, ax2), color='r', lw=0.5)
    txt1 = ax1.text(0.7, 0.9, '', transform=ax1.transAxes)
    txt1.set_text('x=%1.2f, y=%1.2f' % (6, 7))
    
    span1 = SpanSelector(ax1, onselect1, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red'))
    span2 = SpanSelector(ax2, onselect2, 'horizontal', useblit=True, rectprops=dict(alpha=0.5, facecolor='red'))

    plt.show()

main(filename)
